package com.yx1996.dao;

import com.yx1996.dao.impl.UserDaoImpl;
import com.yx1996.domain.User;
import com.yx1996.service.UserService;
import com.yx1996.service.impl.UserServiceImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class testHibernate {

    @Resource(name = "sessionFactory")
    private SessionFactory sf;
    @Test
    //测试hibernate是否导入成功
    public void fun(){

        Configuration cg = new Configuration().configure();
        SessionFactory sessionFactory = cg.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        //-----------------------------------------------------
        //测试hibernate是否可以运行
        User u = new User();
        u.setUser_name("大");
        u.setUser_code("张大");
        u.setUser_password("123321");
        session.save(u);
        //-----------------------------------------------------
        tx.commit();
        session.close();
        sessionFactory.close();
    }

    @Test
    //使用spring中的sessionfactory操作数据库
    public void fun1(){

        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        //-----------------------------------------------------
        //测试hibernate是否可以运行
        User u = new User();
        u.setUser_name("yu");
        u.setUser_code("雨大");
        u.setUser_password("222222");
        session.save(u);
        //-----------------------------------------------------
        tx.commit();
        session.close();
    }

    @Resource(name = "userDao")
    private UserDao ud;

    @Test
    //使用spring整合hibernate操作数据库
    public void fun2(){
        User u = new User();
        u.setUser_code("??");
        User user = ud.getUserByCode(u);
        System.out.println(user);
    }



    @Resource(name = "userService")
    private UserService us;

    @Test
    //测试aop事务
    public void fun3(){
        User u = new User();
        u.setUser_name("yu");
        u.setUser_code("一亿");
        u.setUser_password("222222");
        us.saveUser(u);
    }
}
